import axios from 'axios'
import { useUserStore } from '@/stores/userStore'

const http = axios.create({
    baseURL: '/api',
    timeout: 60000,
    withCredentials: true, // 异步操作携带cookie
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
})

const httpWhiteList: string[] = [
    "/auth/login"
]

// 添加操作拦截器
http.interceptors.request.use(function (config) {
    // 在发送操作之前做些什么
    for (let i = 0; i < httpWhiteList.length; i++) {
        if (config.url === httpWhiteList[i]) {
            return config
        }
    }
    if (config.responseType !== 'blob') {
        window.$loadingBar.start()
    }
    const userStore = useUserStore()
    userStore.loadToken()
    if (!userStore.token || userStore.token === "") {
        window.location.href = "/#/login"
        window.$notification['error']({
            content: `登录有效期超时，请重新登录`,
            meta: `登录有效期超时，请重新登录`,
            duration: 2500,
            keepAliveOnHover: true
        })
        window.$loadingBar.error()
    }
    if (config.headers) {
        config.headers['Authorization'] = userStore.token
    }
    return config;
}, function (error) {
    // 对操作错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
    if (response.headers["authorization"]) {
        const userStore = useUserStore()
        userStore.refreshToken(response.headers["authorization"])
    }
    if (response.status && response.status === 200 && response.data.code === '0') {
        window.$loadingBar.finish()
        return response;
    }
    if (response.headers["content-type"] === 'application/octet-stream') {
        window.$loadingBar.finish()
        return response;
    }
    window.$loadingBar.error()
    if (response.data === "") {
        window.$notification['error']({
            content: `操作异常，请稍后重试`,
            meta: `操作异常，请稍后重试`,
            duration: 2500,
            keepAliveOnHover: true
        })
    } else {
        window.$notification['warning']({
            content: `操作异常[${response.data.code}]`,
            meta: `${response.data.msg}`,
            duration: 2500,
            keepAliveOnHover: true
        })
    }
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    window.$loadingBar.error()
    if (error.response.status && error.response.status === 401) {
        window.location.href = "/#/login"
        window.$notification['error']({
            content: `操作异常[${error.response.data.code}]`,
            meta: `${error.response.data.msg}`,
            duration: 2500,
            keepAliveOnHover: true
        })
        return Promise.reject(error);
    }
    if (error.config.responseType === "blob") {
        const file = new FileReader();
        file.readAsText(error.response.data, 'utf-8');
        file.onload = function () {
            const message = JSON.parse(file.result as string);
            window.$notification['error']({
                content: `操作异常[${message.code}]`,
                meta: `${message.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
        }
        return Promise.reject(error);
    }
    if (error.response.data === "") {
        window.$notification['error']({
            content: `操作异常，请稍后重试`,
            meta: `操作异常，请稍后重试`,
            duration: 2500,
            keepAliveOnHover: true
        })
    } else {
        window.$notification['error']({
            content: `操作异常[${error.response.data.code}]`,
            meta: `${error.response.data.msg}`,
            duration: 2500,
            keepAliveOnHover: true
        })
    }
    return Promise.reject(error);
});

export default http